<?php
// +----------------------------------------------------------------------
// | Exchanges
// +----------------------------------------------------------------------
// | Author: derek <693472824@qq.com> <http://www.bloveambition.com/>
// +----------------------------------------------------------------------

namespace Api\Logic;

/**
 * 订单模型业务逻辑
 *
 * @author derek <693472824@qq.com>
 */
class OrdersLogic extends BaseLogic {

    /**
     * 从微信服务器下载图片到本地，并保存到 orders_record 表，返回 record_id
     */
    public function ajaxDownLoad($mediaID, $model='OrdersRecord'){
    
        $token = api('Util/getToken');
    
        $remote = 'http://file.api.weixin.qq.com/cgi-bin/media/get?access_token='.$token.'&media_id='.$mediaID;
    
        $rootPath = C('UPLOAD_PICTURE_CONFIG.rootPath');
        $savePath = C('UPLOAD_PICTURE_CONFIG.savePath');
    
        if(!$this->checkSavePath($rootPath, $savePath)){
    
            return false;
        }
    
        $subPath = $this->getSubPath(C('UPLOAD_PICTURE_CONFIG.autoSub'), C('UPLOAD_PICTURE_CONFIG.subName'), $rootPath.$savePath, $mediaID);
        $saveName = $this->getSaveName(C('UPLOAD_PICTURE_CONFIG.saveName'), $mediaID);
        $local = $rootPath.$savePath.$subPath.$saveName.'.jpg';
    
        $result = array();
    
        //下载微信服务器图片
        \Org\Net\Http::curlDownload($remote, $local);
    
        //判断文件是否存在
        if(is_file($local)){
    
            $result['name'] = $saveName;
            $result['savename'] = $saveName;
            $result['savepath'] = $subPath;
            $result['fullpath'] = $local;
            $result['media_id'] = $mediaID;
            $result['ext'] = 'jpg';
            $result['mime'] = '';
            $result['size'] = filesize($local);
            $result['md5']  = md5_file($local);
            $result['sha1'] = sha1_file($local);
            $result['uploader'] = '1';
            $result['create_time'] = NOW_TIME;
    
            $recordID = M($model)->data($result)->add();
    
            $result['record_id'] = $recordID;
        }
    
        return $result;
    }

    /**
     * 检测上传目录
     * @param  string $savepath 上传目录
     * @return boolean          检测结果，true-通过，false-失败
     */
    public function checkSavePath($rootPath, $savepath){
        /* 检测并创建目录 */
        if (!$this->mkdir($rootPath, $savepath)) {
            return false;
        } else {
            /* 检测目录是否可写 */
            if (!is_writable($rootPath . $savepath)) {
                $this->error = '上传目录 ' . $savepath . ' 不可写！';
                return false;
            } else {
                return true;
            }
        }
    }
    
    /**
     * 创建目录
     * @param  string $savepath 要创建的穆里
     * @return boolean          创建状态，true-成功，false-失败
     */
    public function mkdir($rootPath, $savepath){
        $dir = $rootPath . $savepath;
    
        if(is_dir($dir)){
            return true;
        }
    
        if(mkdir($dir, 0777, true)){
            return true;
        } else {
            $this->error = "目录 {$savepath} 创建失败！";
            return false;
        }
    }
    
    
    /**
     * 获取子目录的名称
     * @param array $file  上传的文件信息
     */
    private function getSubPath($autoSub, $rule, $savePath, $filename) {
        $subpath = '';
    
        if ($autoSub && !empty($rule)) {
    
            $subpath = $this->getName($rule, $filename) . '/';
    
            if(!empty($subpath) && !$this->mkdir($savePath . $subpath)){
    
                return false;
            }
        }
        return $subpath;
    }
    
    
    /**
     * 根据指定的规则获取文件或目录名称
     * @param  array  $rule     规则
     * @param  string $filename 原文件名
     * @return string           文件或目录名称
     */
    private function getName($rule, $filename){
    
        $name = '';
    
        if(is_array($rule)){ //数组规则
    
            $func     = $rule[0];
            $param    = (array)$rule[1];
            foreach ($param as &$value) {
                $value = str_replace('__FILE__', $filename, $value);
            }
    
            $name = call_user_func_array($func, $param);
    
        } elseif (is_string($rule)){ //字符串规则
            if(function_exists($rule)){
                $name = call_user_func($rule);
            } else {
                $name = $rule;
            }
        }
        return $name;
    }
    
    /**
     * 根据上传文件命名规则取得保存文件名
     * @param string $file 文件信息
     */
    private function getSaveName($rule, $fileName) {
    
        if (empty($rule)) { //保持文件名不变
    
            $savename = $fileName;
    
        } else {
    
            $savename = $this->getName($rule, $fileName);
    
            if(empty($savename)){
                $this->error = '文件命名规则错误！';
                return false;
            }
        }
    
        return $savename;
    }
    
    /**
     * 计算距离维修地址最近的站点
     */
    public function getSite($address = array(), $siteID = ''){
        
        if(empty($address)){
            return null;
        }
        
        if(empty($siteID)){
            $siteArray = M('Worker')->where(array('status'=>'1'))->getField('site_id', true);
            $map['site_id'] = array('in', $siteArray);
        }else{
            $map['site_id'] = $siteID;
        }
        
        $site = M('Site')->where($map)->field('site_id,ROUND(6378.137*2*ASIN(SQRT(POW(SIN(('.$address['latitude']
                .'*PI()/180-latitude*PI()/180)/2),2)+COS('.$address['latitude'].'*PI()/180)*COS(latitude*PI()/180)*POW(SIN(('.$address['longitude']
                .'*PI()/180-longitude*PI()/180)/2),2)))*1000) AS juli')->order('juli')->find();
        
        return $site;
        
    }
    
    /**
     * 计算超范围服务费
     */
    public function getChargePrice($site = array()){
        
        if(!empty($site['juli'])){
            $distance = round($site['juli']/1000, 3);
            $chargeMap['minimum'] = array('ELT', $distance);
            $chargeMap['_string'] = ' (maximum = 0 OR maximum > '.$distance.') ';
            $price = M('Charge')->where($chargeMap)->getField('price');
        }else{
            $price = '0';
        }
        
        return $price;
    }
    
}

?>